package service

import (
	"XiangMu/models"
	"XiangMu/utils"
	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx/v3"
	"net/http"
)

var insertQueue = make(chan []models.UserExcel, 100)

func init() {
	go func() {
		for users := range insertQueue {
			insertUsersToDB(users)
		}
	}()
}
func insertUsersToDB(users []models.UserExcel) {
	tx := models.DB.Begin()
	if tx.Error != nil {

		return
	}
	// 批量插入用户数据
	for _, user := range users {
		var cou int64
		models.DB.Model(models.User{}).Where("xue_hao=?", user.XueHao).Count(&cou)
		if cou > 0 {
			continue
		}
		if err := tx.Table("users").Create(&user).Error; err != nil {
			tx.Rollback() // 回滚事务
			return
		}
	}
	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return
	}
}
func FillByExcel(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 打开上传的文件
	f, err := file.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer f.Close()

	// 解析Excel文件
	xlFile, err := xlsx.OpenReaderAt(f, file.Size)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	sheet := xlFile.Sheets[0]
	var users []models.UserExcel
	for i := 3; i < sheet.MaxRow; i++ {

		//个人信息cell（1）-cell（22）
		row, err := sheet.Row(i)
		if row.GetCell(6).String() == "" {
			continue
		}
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		iden, err := convertScientificToFullNumber(row.GetCell(16).String())
		//获取个人信息
		user := models.UserExcel{
			College:    row.GetCell(1).String(),
			Class:      row.GetCell(2).String(),
			XueHao:     row.GetCell(3).String(),
			Major:      row.GetCell(4).String(),
			Enrollment: row.GetCell(5).String(),
			Name:       row.GetCell(6).String(),
			Occupation: row.GetCell(7).String(),
			Sex:        models.InvertedGenderMap[row.GetCell(8).String()],
			Nation:     row.GetCell(9).String(),
			Birthday:   row.GetCell(11).String(),
			Origin:     row.GetCell(12).String(),
			BirthPlace: row.GetCell(13).String(),
			Political:  row.GetCell(14).String(),
			Title:      row.GetCell(15).String(),
			IdentityId: iden,
			Address:    row.GetCell(17).String(),
			Dorm:       row.GetCell(18).String(),
			Phone:      row.GetCell(19).String(),
			Education:  row.GetCell(20).String(),
			Degree:     row.GetCell(21).String(),
			Account:    row.GetCell(3).String(),
			Password:   "00000",
		}
		//积极分子信息

		users = append(users, user)
	}
	insertQueue <- users
	word, pdf := utils.WordFillByExcel(users[0])
	c.JSON(http.StatusOK, gin.H{
		"message": "文件上传成功",
		"data":    word,
		"pdf":     pdf,
	})
}
